<template>
	<n-modal v-model:show="modalVisible" preset="card" :title="title" class="w-500px">
		<n-form ref="formRef" label-placement="left" :label-width="80" :model="formModel" :rules="rules">
			<n-grid :cols="24" :x-gap="18">
				<n-form-item-grid-item :span="24" label="活动代码" path="actCode">
					<n-input v-model:value="formModel.actCode" />
				</n-form-item-grid-item>
			</n-grid>
			<n-space class="w-full pt-16px" :size="24" justify="end">
				<n-button class="w-72px" @click="closeModal">取消</n-button>
				<n-button class="w-72px" type="primary" @click="handleSubmit">确定</n-button>
			</n-space>
		</n-form>
	</n-modal>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch } from 'vue';
import type { FormInst, FormItemRule } from 'naive-ui';
import { createRequiredFormRule } from '@/utils';
import { SyncIQIYISeckill } from "@/service";

export interface Props {
	/** 弹窗可见性 */
	visible: boolean;
}


defineOptions({ name: 'SyncIqiyiSeckill' });

const props = withDefaults(defineProps<Props>(), {});

interface Emits {
	(e: 'update:visible', visible: boolean): void;
	(e: 'onConfirm'): void;
}

const emit = defineEmits<Emits>();

const modalVisible = computed({
	get() {
		return props.visible;
	},
	set(visible) {
		emit('update:visible', visible);
	}
});
const closeModal = () => {
	modalVisible.value = false;
};

const title = computed(() => {

	return "同步爱奇艺秒杀活动"
});

const formRef = ref<HTMLElement & FormInst>();

type FormModel = {
	'actCode': string
}


const formModel = reactive<FormModel>(createDefaultFormModel());

const rules: Record<keyof FormModel, FormItemRule | FormItemRule[]> = {
	actCode: createRequiredFormRule('请输入活动代码')
};

function createDefaultFormModel(): FormModel {
	return {
		actCode: ''
	};
}

function handleUpdateFormModel(model: Partial<FormModel>) {
	Object.assign(formModel, model);
}

function handleUpdateFormModelByModalType() {
	const defaultFormModel = createDefaultFormModel();
	handleUpdateFormModel(defaultFormModel);
}

async function handleSubmit() {
	await formRef.value?.validate();
	var data = await SyncIQIYISeckill(formModel.actCode);
	if (!data.error) {
		window.$message?.success('保存成功!');
		emit('onConfirm'); // 触发回调事件
		closeModal();
	}
}

watch(
	() => props.visible,
	newValue => {
		if (newValue) {
			handleUpdateFormModelByModalType();
		}
	}
);
</script>

<style scoped></style>
